﻿using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CSGOLauncher
{
    public partial class LauncherForm : Form
    {
        private bool showConfirmationDialog = true; // 默认显示确认对话框

        public LauncherForm()
        {
            InitializeComponent();
            Task.Run(() => UpdateServerStatus("110.42.9.31:27100")); // 模拟服务器1的延迟更新
            Task.Run(() => UpdateServerStatus("110.42.9.31:27200")); // 模拟服务器2的延迟更新
        }

        private async void UpdateServerStatus(string ipAddress)
        {
            try
            {
                PingReply reply = await Task.Run(() => new Ping().Send(ipAddress.Split(':')[0]));
                if (reply != null && reply.Status == IPStatus.Success)
                {
                    Invoke(new Action(() =>
                    {
                        if (ipAddress.Contains(":27100"))
                        {
                            server1StatusLabel.Text = $"延迟: {reply.RoundtripTime}ms";
                        }
                        else if (ipAddress.Contains(":27200"))
                        {
                            server2StatusLabel.Text = $"延迟: {reply.RoundtripTime}ms";
                        }
                    }));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error pinging {ipAddress}: {ex.Message}");
            }
        }

        private void server1Button_Click(object sender, EventArgs e)
        {
            JoinServer("啵咕社区 1服", "110.42.9.31:27100");
        }

        private void server2Button_Click(object sender, EventArgs e)
        {
            JoinServer("啵咕社区 2服", "110.42.9.31:27200");
        }

        private void JoinServer(string serverName, string serverIP)
        {
            if (showConfirmationDialog)
            {
                if (MessageBox.Show($"确定要连接到 {serverName} 吗？", "确认连接", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    ConnectToServer(serverName, serverIP);
                }
            }
            else
            {
                ConnectToServer(serverName, serverIP);
            }
        }

        private void ConnectToServer(string serverName, string serverIP)
        {
            try
            {
                // 建议使用 run/730 +connect，兼容 CS2 和 Steam 启动器
                string url = $"steam://run/730//+connect {serverIP}";
                Process.Start(url);
                statusLabel.Text = $"正在连接 {serverName}...";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}